﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;


namespace CtripSOA
{
    class Utils
    {
        XmlDocument textdoc = new XmlDocument();
		
		public string FormatXml(string sUnformattedXml)
        {
            XmlDocument xd = new XmlDocument();
            xd.LoadXml(sUnformattedXml);
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            XmlTextWriter xtw = null;
            try
            {
                xtw = new XmlTextWriter(sw);
                xtw.Formatting = Formatting.Indented;
                xtw.Indentation = 1;
                xtw.IndentChar = '\t';
                xd.WriteTo(xtw);
            }
            finally
            {
                if (xtw != null)
                    xtw.Close();
            }
            return sb.ToString();
        }
		
		public static string searchText2Side(string leftside, string rightside, string origin) {
			string temp = "";
			
			if (!origin.Contains(leftside) && !origin.Contains(rightside))
				return "";
			
			string[] first_temp = origin.Split(new string[]{leftside}, StringSplitOptions.None);
			if (first_temp.Length > 1)
				temp = origin.Split(new string[]{leftside}, StringSplitOptions.None)[1];
			else
				temp = origin.Split(new string[]{leftside}, StringSplitOptions.None)[0];
			
			string result = temp.Split(new string[]{rightside}, StringSplitOptions.None)[0];
			
			return result;
		}
		
		public void XMLToTree(string xmlDoc,TreeView theTreeView)
        {
            //-------重新对XMLDocument对象赋值
            textdoc.LoadXml(xmlDoc);

            XmlNode root = textdoc.DocumentElement;
            
            foreach (XmlNode subXmlnod in root.ChildNodes)
            {
                TreeNode trerotnod = new TreeNode();
                trerotnod.Text = subXmlnod.Name;
                theTreeView.Nodes.Add(trerotnod);
                TransXML(subXmlnod.ChildNodes, trerotnod);
            }
        }
		 
		private void TransXML(XmlNodeList Xmlnodes,TreeNode partrenod)
        {
            //------遍历XML中的所有节点，仿照treeview节点遍历函数
            foreach (XmlNode xmlnod in Xmlnodes)
            {
                TreeNode subtrnod = new TreeNode();
                
                if (xmlnod.Value == null || xmlnod.Value.Equals("") ) {
                	subtrnod.Text = xmlnod.Name;
                } else {
                	subtrnod.Text = xmlnod.Value;
                }
                
                partrenod.Nodes.Add(subtrnod);

                if (xmlnod.ChildNodes.Count > 0)
                {
                    TransXML(xmlnod.ChildNodes, subtrnod);
                }
            }
        }
    }
}
